package com.zndroid.netmonitor.monitor.impl;

import android.content.Context;
import android.net.TrafficStats;

import androidx.annotation.NonNull;

import com.zndroid.netmonitor.monitor.INetSpeedChangeCallBack;
import com.zndroid.netmonitor.monitor.ISpeed;

import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by lzy on 2020/12/18.
 */
public class MonitorSpeedImpl implements ISpeed {
    private final DecimalFormat showFloatFormat = new DecimalFormat("#.00");
    private final INetSpeedChangeCallBack speedChangeCallBack;

    private double total = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes();
    private Timer timer;
    private int period = 2;//def period is 2 seconds

    public MonitorSpeedImpl(int periodSeconds, @NonNull INetSpeedChangeCallBack speedChangeCallBack) {
        this.period = periodSeconds <= 0 ? 2 : period;
        this.speedChangeCallBack = speedChangeCallBack;
    }

    @Override
    public void startMonitorSpeed(@NonNull Context context) {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                double currentTotal = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes();
                double temp = currentTotal - total;
                speedChangeCallBack.onNetSpeedChanged(temp/period, showSpeed(temp/period));

                total = currentTotal;
            }
        }, period * 1000L, period * 1000L);
    }

    @Override
    public void stopMonitorSpeed(@NonNull Context context) {
        if (null != timer) {
            timer.cancel();
            timer = null;
        }
    }

    protected String showSpeed(double speed) {
        String speedString;
        if (speed >= 1<<30) {
            speedString = showFloatFormat.format(speed / (1<<30)) + "GB/s";
        } else if (speed >= (1<<20)) {
            speedString = showFloatFormat.format(speed / (1<<20)) + "MB/s";
        } else if (speed >= (1<<10)){
            speedString = showFloatFormat.format(speed / (1<<10)) + "KB/s";
        } else {
            speedString = showFloatFormat.format(speed) + "B/s";
        }
        return speedString;
    }
}
